﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Runtime.Serialization;
using LuctecWS.Aspect;
using LuctecWS.DAL;

namespace LuctecWS.Core
{
    [DataContract]
    public class EmailListContact : Base
    {
        [DataMember]
        public int Id { get; set; }
        [DataMember]
        public int EmailListId { get; set; }
        [DataMember]
        public int ContactId { get; set; }

        [LogException]
        public EmailListContact Save()
        {
            using (LuctecEntities context = new LuctecEntities())
            {
                if (Id == 0)
                {
                    var emailListContact = new emaillist_contacts() { Id = this.Id, EmailListId = this.EmailListId, ContactId = this.ContactId };

                    context.AddObject("emaillist_contacts", emailListContact);
                }
                else
                {
                    var emailListContact = context.emaillist_contacts.First(elc => elc.Id == Id);

                    emailListContact.EmailListId = EmailListId;
                    emailListContact.ContactId = ContactId;
                }

                context.SaveChanges();

                if (Id == 0)
                    return AdaptDBCore(context.emaillist_contacts.ToList().Last());
                else
                    return AdaptDBCore(context.emaillist_contacts.ToList().First(elc => elc.Id == Id));
            }
        }

        [LogException]
        public static List<EmailListContact> GetEmailListContacts()
        {
            using (LuctecEntities context = new LuctecEntities())
            {
                var dbEmailListContacts = context.emaillist_contacts.ToList();

                return AdaptDBCore(dbEmailListContacts);
            }
        }

        [LogException]
        private static List<EmailListContact> AdaptDBCore(List<emaillist_contacts> dbEmailListContacts)
        {
            List<EmailListContact> emailListContacts = new List<EmailListContact>();

            if (dbEmailListContacts != null)
                foreach (var dbEmailListContact in dbEmailListContacts)
                {
                    EmailListContact emailListContact = AdaptDBCore(dbEmailListContact);

                    if (emailListContact != null)
                        emailListContacts.Add(emailListContact);
                }

            return emailListContacts;
        }

        [LogException]
        private static EmailListContact AdaptDBCore(emaillist_contacts dbEmailListContact)
        {
            if (dbEmailListContact != null)
                return new EmailListContact() { Id = dbEmailListContact.Id, EmailListId = dbEmailListContact.EmailListId, ContactId = dbEmailListContact.ContactId };

            return null;
        }
    }
}